package com.smart.translator.ui.index;

import android.app.Application;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Looper;
import android.speech.tts.TextToSpeech;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import com.smart.translator.data.model.Language;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import android.util.Log;
import org.json.JSONException;

public class IndexViewModel extends AndroidViewModel {
    private static final String LANG_CACHE_KEY = "allLanguages";
    private static final String PREFS_NAME = "index_prefs";
    private static final String SOURCE_LANG_INDEX_KEY = "sourceLangIndex";
    private static final String TARGET_LANG_INDEX_KEY = "targetLangIndex";

    private final MutableLiveData<List<Language>> languages = new MutableLiveData<>(new ArrayList<>());
    private final MutableLiveData<Integer> sourceLangIndex = new MutableLiveData<>(0);
    private final MutableLiveData<Integer> targetLangIndex = new MutableLiveData<>(1);
    private final MutableLiveData<String> sourceText = new MutableLiveData<>("");
    private final MutableLiveData<String> translatedText = new MutableLiveData<>("");
    private final MutableLiveData<String> error = new MutableLiveData<>("");
    private final MutableLiveData<Boolean> isTranslating = new MutableLiveData<>(false);
    private final MutableLiveData<Integer> wordCount = new MutableLiveData<>(0);
    private final SharedPreferences prefs;
    private MediaPlayer mediaPlayer;
    private Context context;

    public IndexViewModel(@NonNull Application application) {
        super(application);
        context = application;
        prefs = application.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
        loadPrefs();
        loadLanguages();
    }

    private void loadPrefs() {
        sourceLangIndex.setValue(prefs.getInt(SOURCE_LANG_INDEX_KEY, 0));
        targetLangIndex.setValue(prefs.getInt(TARGET_LANG_INDEX_KEY, 1));
    }
    private void savePref(String key, int value) {
        prefs.edit().putInt(key, value).apply();
    }

    private void loadLanguages() {
        // 先尝试本地缓存
        SharedPreferences homePrefs = getApplication().getSharedPreferences("home_prefs", Context.MODE_PRIVATE);
        String cache = homePrefs.getString(LANG_CACHE_KEY, null);
        if (cache != null) {
            setLangOptionsFromJson(cache);
        }
        // 拉取最新
        new Thread(() -> {
            try {
                // 获取服务器地址
                String serverUrl = getServerUrl();
                
                URL url = new URL("http://" + serverUrl + "/languages");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(3000);
                conn.setReadTimeout(3000);
                int code = conn.getResponseCode();
                if (code == 200) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) sb.append(line);
                    reader.close();
                    String json = sb.toString();
                    homePrefs.edit().putString(LANG_CACHE_KEY, json).apply();
                    setLangOptionsFromJson(json);
                }
            } catch (Exception ignored) {}
        }).start();
    }
    
    /**
     * 获取服务器地址
     */
    private String getServerUrl() {
        try {
            android.content.SharedPreferences prefs = getApplication().getSharedPreferences("app_config", Context.MODE_PRIVATE);
            return prefs.getString("server_url", "qixin.yeshan.fun");
        } catch (Exception e) {
            Log.e("IndexViewModel", "获取服务器地址失败", e);
            return "qixin.yeshan.fun";
        }
    }
	
	
	 private void setLangOptionsFromJson(String json) {
        try {
            JSONArray arr = new JSONArray(json);
            List<Language> list = new ArrayList<>();
            for (int i = 0; i < arr.length(); i++) {
                JSONObject obj = arr.getJSONObject(i);
                list.add(new Language(obj.optString("code"), obj.optString("name")));
            }
            new Handler(Looper.getMainLooper()).post(() -> languages.setValue(list));
        } catch (Exception ignored) {}
    }


    public LiveData<List<Language>> getLanguages() { return languages; }
    public LiveData<Integer> getSourceLangIndex() { return sourceLangIndex; }
    public LiveData<Integer> getTargetLangIndex() { return targetLangIndex; }
    public LiveData<String> getSourceText() { return sourceText; }
    public LiveData<String> getTranslatedText() { return translatedText; }
    public LiveData<String> getError() { return error; }
    public LiveData<Boolean> getIsTranslating() { return isTranslating; }
    public LiveData<Integer> getWordCount() { return wordCount; }

    public void setSourceLangIndex(int idx) { sourceLangIndex.setValue(idx); savePref(SOURCE_LANG_INDEX_KEY, idx); }
    public void setTargetLangIndex(int idx) { targetLangIndex.setValue(idx); savePref(TARGET_LANG_INDEX_KEY, idx); }
    public void setSourceText(String text) {
        sourceText.setValue(text);
        wordCount.setValue(text != null ? text.length() : 0);
    }
    public void clearText() { setSourceText(""); }
    public void pasteText() {
        ClipboardManager clipboard = (ClipboardManager) getApplication().getSystemService(Context.CLIPBOARD_SERVICE);
        if (clipboard != null && clipboard.hasPrimaryClip()) {
            ClipData clip = clipboard.getPrimaryClip();
            if (clip != null && clip.getItemCount() > 0) {
                CharSequence paste = clip.getItemAt(0).coerceToText(getApplication());
                setSourceText(paste != null ? paste.toString() : "");
            }
        }
    }
    public void copyResult() {
        String text = translatedText.getValue();
        if (text != null && !text.isEmpty()) {
            ClipboardManager clipboard = (ClipboardManager) getApplication().getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData clip = ClipData.newPlainText("翻译结果", text);
            clipboard.setPrimaryClip(clip);
            Toast.makeText(getApplication(), "已复制", Toast.LENGTH_SHORT).show();
        }
    }
    public void switchLanguages() {
        Integer src = sourceLangIndex.getValue();
        Integer tgt = targetLangIndex.getValue();
        if (src != null && tgt != null) {
            setSourceLangIndex(tgt);
            setTargetLangIndex(src);
        }
    }
    public void translate() {
        if (isTranslating.getValue() != null && isTranslating.getValue()) return;
        String text = sourceText.getValue();
        if (text == null || text.trim().isEmpty()) {
            error.setValue("请输入要翻译的内容");
            return;
        }
        isTranslating.setValue(true);
        new Thread(() -> {
            try {
                List<Language> langs = languages.getValue();
                int sIdx = sourceLangIndex.getValue() != null ? sourceLangIndex.getValue() : 0;
                int tIdx = targetLangIndex.getValue() != null ? targetLangIndex.getValue() : 1;
                String from_lang = langs != null && sIdx < langs.size() ? langs.get(sIdx).getCode() : "";
                String to_lang = langs != null && tIdx < langs.size() ? langs.get(tIdx).getCode() : "";
                
                // 获取服务器地址
                String serverUrl = getServerUrl();
                
                JSONObject req = new JSONObject();
                req.put("text", text.trim());
                req.put("from_lang", from_lang);
                req.put("to_lang", to_lang);
                URL url = new URL("http://" + serverUrl + "/translate");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setDoOutput(true);
                conn.getOutputStream().write(req.toString().getBytes());
                int code = conn.getResponseCode();
                if (code == 200) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) sb.append(line);
                    reader.close();
                    JSONObject resp = new JSONObject(sb.toString());
                    if (resp.has("result") && resp.getJSONObject("result").has("trans_result")) {
                        String dst = resp.getJSONObject("result").getJSONObject("trans_result").optString("dst", "");
                        new Handler(Looper.getMainLooper()).post(() -> translatedText.setValue(dst));
                    } else {
                        new Handler(Looper.getMainLooper()).post(() -> translatedText.setValue("翻译失败"));
                    }
                } else {
                    new Handler(Looper.getMainLooper()).post(() -> translatedText.setValue("翻译失败"));
                }
            } catch (Exception e) {
                new Handler(Looper.getMainLooper()).post(() -> translatedText.setValue("翻译失败"));
            } finally {
                new Handler(Looper.getMainLooper()).post(() -> isTranslating.setValue(false));
            }
        }).start();
    }
    public void speakResult() {
        String text = translatedText.getValue();
        if (text == null || text.isEmpty()) {
            error.setValue("无音频内容");
            return;
        }
        new Thread(() -> {
            try {
                // 获取服务器地址
                String serverUrl = getServerUrl();
                
                JSONObject req = new JSONObject();
                req.put("text", text);
                URL url = new URL("http://" + serverUrl + "/tts/url");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setDoOutput(true);
                conn.getOutputStream().write(req.toString().getBytes());
                int code = conn.getResponseCode();
                if (code == 200) {
                    BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    StringBuilder sb = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) sb.append(line);
                    reader.close();
                    JSONObject resp = new JSONObject(sb.toString());
                    String urlStr = resp.optString("url", "");
                    if (urlStr.startsWith("/")) urlStr = "http://" + serverUrl + urlStr;
                    playMp3(urlStr);
                } else {
                    error.postValue("获取音频地址失败");
                }
            } catch (Exception e) {
                error.postValue("获取音频地址失败");
            }
        }).start();
    }
    private void playMp3(String url) {
        try {
            if (mediaPlayer != null) {
                mediaPlayer.release();
            }
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(url);
            mediaPlayer.setOnPreparedListener(MediaPlayer::start);
            mediaPlayer.prepareAsync();
        } catch (Exception e) {
            error.postValue("播放失败");
        }
    }
    @Override
    protected void onCleared() {
        if (mediaPlayer != null) mediaPlayer.release();
        super.onCleared();
    }
} 